<template>
  <div class="venue-container">
    <van-nav-bar title="场地管理" left-arrow @click-left="$router.back()" />
    
    <div class="venue-content">
      <!-- 搜索栏 -->
      <van-search 
        v-model="searchValue" 
        placeholder="搜索场地名称"
        @search="onSearch"
        @clear="onClear"
      />
      
      <!-- 添加按钮 -->
      <van-button 
        type="primary" 
        block 
        class="add-btn"
        @click="showAddDialog = true"
      >
        <van-icon name="plus" /> 添加场地
      </van-button>
      
      <!-- 场地列表 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          v-for="item in venueList"
          :key="item.id"
          :title="item.name"
          :desc="`编号: ${item.code} | 类型: ${item.type} | 容量: ${item.capacity}人`"
          :thumb="item.image"
        >
          <template #tags>
            <van-tag :type="item.status === 'available' ? 'success' : 'danger'">
              {{ item.status === 'available' ? '可用' : '维护中' }}
            </van-tag>
            <van-tag type="primary">{{ item.building }}</van-tag>
          </template>
          <template #footer>
            <van-button size="mini" @click="viewVenue(item)">详情</van-button>
            <van-button size="mini" @click="editVenue(item)">编辑</van-button>
            <van-button size="mini" type="danger" @click="deleteVenue(item)">删除</van-button>
          </template>
        </van-card>
      </van-list>
    </div>
    
    <!-- 添加/编辑弹窗 -->
    <van-popup 
      v-model:show="showAddDialog" 
      position="bottom" 
      :style="{ height: '80%' }"
      round
      closeable
    >
      <div class="form-container">
        <h3>{{ editingVenue ? '编辑场地' : '添加场地' }}</h3>
        <van-form @submit="onSubmit">
          <van-field
            v-model="formData.name"
            name="name"
            label="场地名称"
            placeholder="请输入场地名称"
            :rules="[{ required: true, message: '请输入场地名称' }]"
          />
          <van-field
            v-model="formData.code"
            name="code"
            label="场地编号"
            placeholder="请输入场地编号"
            :rules="[{ required: true, message: '请输入场地编号' }]"
          />
          <van-field
            v-model="formData.building"
            name="building"
            label="所在建筑"
            placeholder="请输入所在建筑"
            :rules="[{ required: true, message: '请输入所在建筑' }]"
          />
          <van-field
            v-model="formData.floor"
            name="floor"
            label="楼层"
            type="number"
            placeholder="请输入楼层"
            :rules="[{ required: true, message: '请输入楼层' }]"
          />
          <van-field name="type" label="场地类型">
            <template #input>
              <van-radio-group v-model="formData.type" direction="horizontal">
                <van-radio name="classroom">教室</van-radio>
                <van-radio name="lab">实验室</van-radio>
                <van-radio name="auditorium">报告厅</van-radio>
                <van-radio name="gym">体育场馆</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="formData.capacity"
            name="capacity"
            label="容量"
            type="number"
            placeholder="请输入容量"
            :rules="[{ required: true, message: '请输入容量' }]"
          />
          <van-field name="status" label="状态">
            <template #input>
              <van-radio-group v-model="formData.status" direction="horizontal">
                <van-radio name="available">可用</van-radio>
                <van-radio name="maintenance">维护中</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field name="facilities" label="设施">
            <template #input>
              <van-checkbox-group v-model="formData.facilities" direction="horizontal">
                <van-checkbox name="projector">投影仪</van-checkbox>
                <van-checkbox name="computer">电脑</van-checkbox>
                <van-checkbox name="whiteboard">白板</van-checkbox>
                <van-checkbox name="microphone">话筒</van-checkbox>
                <van-checkbox name="aircon">空调</van-checkbox>
              </van-checkbox-group>
            </template>
          </van-field>
          <van-field
            v-model="formData.description"
            name="description"
            label="描述"
            type="textarea"
            placeholder="请输入场地描述"
            rows="3"
          />
          <div class="form-buttons">
            <van-button block type="primary" native-type="submit">
              {{ editingVenue ? '更新' : '添加' }}
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
    
    <!-- 详情弹窗 -->
    <van-popup 
      v-model:show="showDetailDialog" 
      position="bottom" 
      :style="{ height: '70%' }"
      round
      closeable
    >
      <div class="detail-container" v-if="selectedVenue">
        <h3>场地详情</h3>
        <van-cell-group>
          <van-cell title="场地名称" :value="selectedVenue.name" />
          <van-cell title="场地编号" :value="selectedVenue.code" />
          <van-cell title="所在建筑" :value="selectedVenue.building" />
          <van-cell title="楼层" :value="`${selectedVenue.floor}楼`" />
          <van-cell title="场地类型" :value="getTypeLabel(selectedVenue.type)" />
          <van-cell title="容量" :value="`${selectedVenue.capacity}人`" />
          <van-cell title="状态" :value="selectedVenue.status === 'available' ? '可用' : '维护中'" />
          <van-cell title="设施" :value="getFacilitiesLabel(selectedVenue.facilities)" />
          <van-cell title="描述" :value="selectedVenue.description || '无'" />
        </van-cell-group>
      </div>
    </van-popup>
    
    <van-tabbar v-model="activeTab" fixed>
      <van-tabbar-item icon="wap-home-o" to="/dashboard">首页</van-tabbar-item>
      <van-tabbar-item icon="calendar-o" to="/calendar">日历</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/schedule">排课</van-tabbar-item>
      <van-tabbar-item icon="manager-o" to="/master/teacher">管理</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'

const searchValue = ref('')
const loading = ref(false)
const finished = ref(false)
const venueList = ref([])
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const editingVenue = ref(null)
const selectedVenue = ref(null)
const activeTab = ref(3)

const formData = ref({
  name: '',
  code: '',
  building: '',
  floor: '',
  type: 'classroom',
  capacity: '',
  status: 'available',
  facilities: [],
  description: ''
})

const typeLabels = {
  classroom: '教室',
  lab: '实验室',
  auditorium: '报告厅',
  gym: '体育场馆'
}

const facilityLabels = {
  projector: '投影仪',
  computer: '电脑',
  whiteboard: '白板',
  microphone: '话筒',
  aircon: '空调'
}

const onLoad = async () => {
  try {
    // 模拟加载数据
    setTimeout(() => {
      if (venueList.value.length === 0) {
        venueList.value = [
          { 
            id: 1, 
            name: '多媒体教室A101', 
            code: 'A101', 
            building: '教学楼A',
            floor: 1,
            type: 'classroom',
            capacity: 60,
            status: 'available',
            facilities: ['projector', 'computer', 'whiteboard', 'aircon'],
            description: '配备先进多媒体设备的大型教室',
            image: 'https://img.yzcdn.cn/vant/cat.jpeg'
          },
          { 
            id: 2, 
            name: '计算机实验室B201', 
            code: 'B201', 
            building: '实验楼B',
            floor: 2,
            type: 'lab',
            capacity: 40,
            status: 'available',
            facilities: ['computer', 'projector', 'aircon'],
            description: '计算机专业实验室，配备40台电脑'
          },
          { 
            id: 3, 
            name: '学术报告厅', 
            code: 'C001', 
            building: '行政楼C',
            floor: 1,
            type: 'auditorium',
            capacity: 200,
            status: 'maintenance',
            facilities: ['projector', 'microphone', 'aircon'],
            description: '大型学术活动场所，音响设备维护中'
          }
        ]
      }
      loading.value = false
      finished.value = true
    }, 1000)
  } catch (error) {
    showToast('加载失败')
    loading.value = false
  }
}

const onSearch = (value) => {
  // 实现搜索逻辑
  console.log('搜索:', value)
}

const onClear = () => {
  searchValue.value = ''
}

const viewVenue = (item) => {
  selectedVenue.value = item
  showDetailDialog.value = true
}

const editVenue = (item) => {
  editingVenue.value = item
  formData.value = { ...item }
  showAddDialog.value = true
}

const deleteVenue = async (item) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除场地"${item.name}"吗？`,
    })
    
    // 这里应该调用删除API
    const index = venueList.value.findIndex(v => v.id === item.id)
    if (index > -1) {
      venueList.value.splice(index, 1)
      showToast('删除成功')
    }
  } catch {
    // 用户取消
  }
}

const onSubmit = async () => {
  try {
    if (editingVenue.value) {
      // 编辑
      const index = venueList.value.findIndex(v => v.id === editingVenue.value.id)
      if (index > -1) {
        venueList.value[index] = { 
          ...editingVenue.value, 
          ...formData.value,
          floor: parseInt(formData.value.floor),
          capacity: parseInt(formData.value.capacity)
        }
      }
      showToast('更新成功')
    } else {
      // 添加
      const newVenue = {
        id: Date.now(),
        ...formData.value,
        floor: parseInt(formData.value.floor),
        capacity: parseInt(formData.value.capacity)
      }
      venueList.value.unshift(newVenue)
      showToast('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    showToast('操作失败')
  }
}

const resetForm = () => {
  formData.value = {
    name: '',
    code: '',
    building: '',
    floor: '',
    type: 'classroom',
    capacity: '',
    status: 'available',
    facilities: [],
    description: ''
  }
  editingVenue.value = null
}

const getTypeLabel = (type) => {
  return typeLabels[type] || type
}

const getFacilitiesLabel = (facilities) => {
  if (!facilities || facilities.length === 0) return '无'
  return facilities.map(f => facilityLabels[f] || f).join('、')
}

onMounted(() => {
  onLoad()
})
</script>

<style lang="scss" scoped>
.venue-container {
  padding-bottom: 50px;
}

.venue-content {
  padding: $padding-md;
}

.add-btn {
  margin: $padding-md 0;
  
  .van-icon {
    margin-right: 4px;
  }
}

.van-card {
  margin-bottom: $padding-sm;
  border-radius: $border-radius-md;
  overflow: hidden;
  
  :deep(.van-card__footer) {
    display: flex;
    gap: $padding-xs;
  }
  
  :deep(.van-card__header) {
    .van-tag {
      margin-right: $padding-xs;
    }
  }
}

.form-container, .detail-container {
  padding: $padding-lg;
  
  h3 {
    text-align: center;
    margin-bottom: $padding-lg;
    color: $text-color;
  }
}

.form-buttons {
  margin-top: $padding-lg;
}

:deep(.van-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: $padding-xs;
}

:deep(.van-radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: $padding-xs;
}
</style>